﻿// LinqToEntitiesDomainServiceEx.cs
//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.ServiceModel.DomainServices.Server;

namespace System.ServiceModel.DomainServices.EntityFramework {

    /// <summary>
    /// An extension of the standard LinqToEntitiesDomainService that adds the ability to
    /// queue work within insert/update/delete operations that should be performed upon a
    /// successful submit to the database.
    /// </summary>
    /// <typeparam name="TObjectContext">The type of the Entity Framework ObjectContext to use.</typeparam>
    public abstract class LinqToEntitiesDomainServiceEx<TObjectContext> : LinqToEntitiesDomainService<TObjectContext> where TObjectContext : ObjectContext, new() {

        private List<Action> _actions;

        /// <summary>
        /// Queues the specified action to be invoked upon successful submit.
        /// </summary>
        /// <param name="action">The action to invoke.</param>
        protected void QueueOnSubmit(Action action) {
            if (action == null) {
                throw new ArgumentNullException("action");
            }

            if (_actions == null) {
                _actions = new List<Action>();
            }
            _actions.Add(action);
        }

        /// <internalonly />
        public override bool Submit(ChangeSet changeSet) {
            bool result = base.Submit(changeSet);

            if (result && (_actions != null)) {
                foreach (Action action in _actions) {
                    action();
                }
            }

            return result;
        }
    }
}
